package com.zoho.daliansheng.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zoho.daliansheng.common.U8SystemRecord;
import com.zoho.daliansheng.common.ZohoRecord;
import com.zoho.daliansheng.config.CRMPathConfig;
import com.zoho.daliansheng.config.CRMSqlQuery;
import com.zoho.daliansheng.config.U8SystemPathConfig;
import com.zoho.daliansheng.dlcr.DlcrU8WebService;
import com.zoho.daliansheng.dlcr.DlcrU8WebServiceSoap;
import com.zoho.daliansheng.utils.CommonUtil;
import com.zoho.daliansheng.utils.CrmApiUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Service
public class DispatchDetailListServiceImpl implements DispatchDetailListService {

    ZohoRecord zohoRecord;

    U8SystemRecord u8SystemRecord;

    U8SystemPathConfig u8SystemPathConfig;

    CRMPathConfig crmPathConfig;

    CRMSqlQuery crmSqlQuery;

    public DispatchDetailListServiceImpl(ZohoRecord zohoRecord, U8SystemRecord u8SystemRecord, U8SystemPathConfig u8SystemPathConfig, CRMPathConfig crmPathConfig, CRMSqlQuery crmSqlQuery) {
        this.zohoRecord = zohoRecord;
        this.u8SystemRecord = u8SystemRecord;
        this.u8SystemPathConfig = u8SystemPathConfig;
        this.crmPathConfig = crmPathConfig;
        this.crmSqlQuery = crmSqlQuery;
    }

    @Override
    public void synU8Data(String webServiceUrl, String accountCode, String companyName, List<JSONObject> productList, List<JSONObject> warehouseData,
                          List<JSONObject> currentStockList, int maxVersion, int queryMaxVersion,
                          List<JSONObject> batchCurrentStock, String versionCrmId) throws MalformedURLException {

        String detailModuleName = crmPathConfig.getDispatchDetailModuleName(); // 要同步的模块名称  发货单明细
        // 比较数据
        List<JSONObject> insertModuleList = new ArrayList<>();
        List<JSONObject> updateModuleList = new ArrayList<>();
        List<String> deleteModuleList = new ArrayList<>();
        List<JSONObject> insertList = new ArrayList<>();
        List<JSONObject> updateList = new ArrayList<>();
        List<JSONObject> deleteList = new ArrayList<>();

        if (maxVersion == -1) {
            //List<JSONObject> aaaa = new ArrayList<>();
            for (JSONObject erpData : batchCurrentStock) {
                String dlid = erpData.getString("dlid");

                //List<String> list = new ArrayList<>();
                //list.add("1000001370");
                //if (list.contains(dlid)) {
                String selectQuery = crmSqlQuery.getDispatchSqlByErpId(dlid, companyName);
                List<JSONObject> searchList = CrmApiUtil.COQLQuery(zohoRecord.getAccessToken(), selectQuery);
                if (searchList.size() > 0) {
                    JSONObject jsonObject = searchList.get(0);
                    String crmId = jsonObject.getString("id");
                    erpData.put("crmId", crmId);
                }
                //// System.out.println("erpData.toJSONString() = " + erpData.toJSONString());
                //aaaa.add(erpData);
                //}
            }

            insertModuleList = batchCurrentStock;
            insertList = batchCurrentStock;
            //insertModuleList = aaaa;
            //insertList = aaaa;
        } else {
            for (JSONObject erpData : batchCurrentStock) {

                // sys_change_operation 该字段非常关键,记录了记录的变动类型,I=Insert、U=Update、D=Delete
                String operation = erpData.getString("sys_change_operation");
                //System.out.println("operation = " + operation);
                String dlid = erpData.getString("dlid");
                //System.out.println("dlid = " + dlid);
                String selectQuery = crmSqlQuery.getDispatchSqlByErpId(dlid, companyName);
                List<JSONObject> searchList = CrmApiUtil.COQLQuery(zohoRecord.getAccessToken(), selectQuery);
                // 存储无头表体数据
                if (searchList.size() == 0) {
                    String crmId = insertHeadData(dlid, companyName);
                    if (StringUtils.isNotBlank(crmId)) {
                        JSONObject temp = new JSONObject();
                        temp.put("id", crmId);
                        searchList.add(temp);
                    }
                }

                //System.out.println("searchList.size() = " + searchList.size());
                if ("I".equals(operation)) {
                    if (searchList.size() > 0) {
                        JSONObject jsonObject = searchList.get(0);
                        String crmId = jsonObject.getString("id");
                        erpData.put("crmId", crmId);
                        insertList.add(erpData);
                        insertModuleList.add(erpData);
                    }
                } else if ("U".equals(operation)) {
                    if (searchList.size() > 0) {
                        JSONObject jsonObject = searchList.get(0);
                        String crmId = jsonObject.getString("id");
                        erpData.put("crmId", crmId);
                        updateList.add(erpData);
                        String pk_id = erpData.getString("pk_id");
                        //System.out.println("pk_id = " + pk_id);
                        // 去发货单明细模块里查
                        String detail_selectQuery = crmSqlQuery.getDispatchDetailSqlByErpId(pk_id, companyName);
                        List<JSONObject> filterDetailList = CrmApiUtil.COQLQuery(zohoRecord.getAccessToken(), detail_selectQuery);
                        //System.out.println("filterDetailList.size() = " + filterDetailList.size());
                        if (filterDetailList.size() > 0) {
                            JSONObject detail = filterDetailList.get(0);
                            String detailId = detail.getString("id");
                            erpData.put("detailCRMId", detailId);
                            updateModuleList.add(erpData);
                        }
                    }
                } else if ("D".equals(operation)) {
                    //log.info("发货单明细删除数据={}", erpData.toJSONString());

                    String pk_id = erpData.getString("pk_id");
                    String json = "[" + pk_id + "]";
                    DlcrU8WebService webService = new DlcrU8WebService(new URL(webServiceUrl));
                    DlcrU8WebServiceSoap api = webService.getDlcrU8WebServiceSoap();
                    String dlidArray = api.getDlidFromDeletedAutoids(json);
                    //log.info("发货单明细删除dlidArray={}", dlidArray);
                    JSONArray array = JSONArray.parseArray(dlidArray);
                    if (array.size() > 0) {
                        List<JSONObject> list = array.toJavaList(JSONObject.class);
                        JSONObject jsonObject = list.get(0);
                        String dlidByPK = jsonObject.getString("dlid");
                        if (StringUtils.isNotBlank(dlidByPK)) {
                            String pk_selectQuery = crmSqlQuery.getDispatchSqlByErpId(dlidByPK, companyName);
                            List<JSONObject> data = CrmApiUtil.COQLQuery(zohoRecord.getAccessToken(), pk_selectQuery);
                            //log.info("发货单[子表单]明细删除data={}", JSONObject.toJSONString(data));
                            if (data.size() > 0) {
                                JSONObject temp = data.get(0);
                                String crmId = temp.getString("id");
                                erpData.put("crmId", crmId);
                                deleteList.add(erpData);
                            }
                            String detail_pk_selectQuery = crmSqlQuery.getDispatchDetailSqlByErpId(pk_id, companyName);
                            List<JSONObject> detailData = CrmApiUtil.COQLQuery(zohoRecord.getAccessToken(), detail_pk_selectQuery);
                            //log.info("发货单[明细模块]删除data={}", JSONObject.toJSONString(detailData));
                            if (detailData.size() > 0) {
                                JSONObject temp = detailData.get(0);
                                String crmId = temp.getString("id");
                                deleteModuleList.add(crmId);
                            }
                        }
                    }
                }
                //System.out.println("------------------------------");
            }
        }

        // 5 字段映射
        // 销售发货单明细模块，新增
        List<JSONObject> crm_insertModuleList = getCrmMappingDetailData(insertModuleList, companyName, productList, "新增");
        //System.out.println("新增_明细模块数量.size() = " + crm_insertModuleList.size());
        List<JSONObject> crm_updateModuleList = getCrmMappingDetailData(updateModuleList, companyName, productList, "修改");
        //System.out.println("修改_明细模块数量.size() = " + crm_updateModuleList.size());
        //System.out.println("删除_明细模块数量.size() = " + deleteModuleList.size());

        //System.out.println("子表单新增数量.size() = " + insertList.size());
        //System.out.println("子表单修改数量.size() = " + updateList.size());
        //System.out.println("子表单删除数量.size() = " + deleteList.size());

        log.info("子表单新增数据.data = " + JSONObject.toJSONString(insertList));
        log.info("子表单修改数据.data = " + JSONObject.toJSONString(updateList));
        //System.out.println("--------------");
        // 发货单子表单，增删改
        getSubFormData(insertList, "I", warehouseData, currentStockList, productList, companyName); // 销售发货单模块，新增子表单
        getSubFormData(updateList, "U", warehouseData, currentStockList, productList, companyName); // 销售发货单模块，修改子表单
        getSubFormData(deleteList, "D", warehouseData, currentStockList, productList, companyName); // 销售发货单模块，修改子表单

        // 6 批量操作
        // 发货单明细模块 新增
        CrmApiUtil.batchInsertDataByList(zohoRecord.getAccessToken(), crm_insertModuleList, detailModuleName); // 发货单明细模块，也同步一份新数据
        // 发货单明细模块 修改
        CrmApiUtil.batchUpdateDataByList(zohoRecord.getAccessToken(), crm_updateModuleList, detailModuleName); // 发货单明细模块，修改
        // 发货单明细模块 删除
        if (deleteModuleList.size() > 0) {
            CrmApiUtil.batchDeleteModelData(zohoRecord.getAccessToken(), detailModuleName, deleteModuleList);
        }

        // 7 最大版本号回传
        if (queryMaxVersion != maxVersion) {
            CrmApiUtil.saveMaxVersion(zohoRecord.getAccessToken(), versionCrmId, queryMaxVersion, crmPathConfig.getMaxVersionModuleName());
        }
    }

    // 如果出现无头表体数据，先新增表头
    private String insertHeadData(String dlid, String companyName) {
        JSONObject insertData = new JSONObject();
        insertData.put("Name", "无头表体数据_临时添加");
        insertData.put("pk_id", dlid);
        insertData.put("erp_id", dlid);
        insertData.put("KHCompany", companyName);
        if (StringUtils.isNotBlank(dlid)) {
            JSONArray insertArray = new JSONArray();
            insertArray.add(insertData);
            JSONObject jsonObject = CrmApiUtil.batchInsertData(zohoRecord.getAccessToken(), insertArray, crmPathConfig.getDispatchModuleName());
            if (Objects.nonNull(jsonObject)) {
                List<JSONObject> tempList = jsonObject.getJSONArray("data").toJavaList(JSONObject.class);
                if (tempList.size() > 0) {
                    return tempList.get(0).getJSONObject("details").getString("id");
                }
            }
        }
        return "";
    }

    private void getSubFormData(List<JSONObject> erpList, String operation, List<JSONObject> warehouseData,
                                List<JSONObject> currentStockList, List<JSONObject> productList, String companyName) {
        List<JSONObject> list = new ArrayList<>();
        for (JSONObject erpData : erpList) {

            String crmId = erpData.getString("crmId"); // 发货单数据id
            String autoId; // erp表体数据id
            if (operation.equals("D")) {
                autoId = erpData.getString("pk_id"); // erp表体数据id
            } else {
                autoId = erpData.getString("autoid"); // erp表体数据id

            }
            if (StringUtils.isBlank(crmId) && !operation.equals("D")) { // 如果是删除，接口里不会有这个字段
                continue;
            }

            String dispatchModuleName = crmPathConfig.getDispatchModuleName(); // 要同步的模块名称  发货单
            JSONObject dataById = CrmApiUtil.getDataById(zohoRecord.getAccessToken(), crmPathConfig.getDispatchModuleName(), crmId);
            if (Objects.nonNull(dataById)) {
                JSONObject tempJson = new JSONObject();

                JSONArray linkingModule9 = dataById.getJSONArray("LinkingModule9");
                // System.out.println("JSONObject.toJSONString(linkingModule9) = " + JSONObject.toJSONString(linkingModule9));
                if (Objects.nonNull(linkingModule9) && linkingModule9.size() > 0) {
                    List<JSONObject> tempList = linkingModule9.toJavaList(JSONObject.class); // CRM子表单原来的数据

                    // 子表单本身有48个字段，过滤只剩下所需字段
                    tempList = filterList(tempList);
                    JSONObject subFormMappingData;
                    switch (operation) {
                        case "I":  // 新增
                            insertSubForm(warehouseData, currentStockList, productList, companyName, erpData, crmId, dispatchModuleName, tempJson);
                            break;
                        case "U": { // 修改
                            subFormMappingData = getSubFormMappingData(erpData, warehouseData, currentStockList, productList, companyName);
                            subFormMappingData.put("detail_operator_type", "修改");  // 明细操作类型
                            // 获取子表单，操作类型是新增的子表单数据id
                            List<JSONObject> temp = tempList.stream().filter(object ->
                                    Objects.nonNull(object.getString("autoid")) && object.getString("autoid").equals(autoId) &&
                                            "新增".equals(object.getString("detail_operator_type"))
                            ).collect(Collectors.toList());
                            if (temp.size() > 0) {
                                JSONObject crmSubFormData = temp.get(0);
                                // 覆盖原有子表单的值
                                crmSubFormData.putAll(subFormMappingData);
                                List<JSONObject> newUpdateList = new ArrayList<>();
                                newUpdateList.add(crmSubFormData);

                                // 更新子表单，不然下次循环查询的数据，还是未修改的状态
                                List<JSONObject> tempUpdateList = new ArrayList<>();
                                tempJson.put("id", crmId);
                                tempJson.put("LinkingModule9", newUpdateList);
                                tempUpdateList.add(tempJson);
                                //System.out.println("CRM子表单修改数据 = " + JSONObject.toJSONString(tempUpdateList));
                                CrmApiUtil.batchUpdateDataByList(zohoRecord.getAccessToken(), tempUpdateList, dispatchModuleName);
                            }
                            break;
                        }
                        case "D": { // 删除
                            List<JSONObject> temp = tempList.stream().filter(object ->
                                    Objects.nonNull(object.getString("autoid")) && object.getString("autoid").equals(autoId)).collect(Collectors.toList());
                            if (temp.size() > 0) {
                                String subFormId = temp.get(0).getString("autoid");
                                List<JSONObject> newDeleteList = new ArrayList<>();
                                for (JSONObject jsonObject : tempList) {
                                    if (!jsonObject.getString("autoid").equals(subFormId)) {
                                        jsonObject.remove("id"); // 把之前的子表单数据id置空
                                        newDeleteList.add(jsonObject);
                                    }
                                }
                                tempJson.put("id", crmId);
                                tempJson.put("LinkingModule9", newDeleteList);
                                list.add(tempJson);
                                deleteSubForm(list, dispatchModuleName);
                                list = new ArrayList<>();
                            }
                            break;
                        }
                    }
                } else {
                    insertSubForm(warehouseData, currentStockList, productList, companyName, erpData, crmId, dispatchModuleName, tempJson);
                }
            }
        }
    }

    // 子表单删除
    private void deleteSubForm(List<JSONObject> crm_deleteList, String dispatchModuleName) {
        List<JSONObject> crm_empty_List = getEmptyLinkList(crm_deleteList);
        // 发货单模块 删除：先把子表单置空修改一次，在将数据同步进去，修改一次
        CrmApiUtil.batchUpdateDataByList(zohoRecord.getAccessToken(), crm_empty_List, dispatchModuleName);// 子表单先置空
        CrmApiUtil.batchUpdateDataByList(zohoRecord.getAccessToken(), crm_deleteList, dispatchModuleName); // 在更新子表单

    }

    // 子表单新增数据
    private void insertSubForm(List<JSONObject> warehouseData, List<JSONObject> currentStockList, List<JSONObject> productList, String companyName, JSONObject erpData, String crmId, String dispatchModuleName, JSONObject tempJson) {
        JSONObject subFormMappingData;
        subFormMappingData = getSubFormMappingData(erpData, warehouseData, currentStockList, productList, companyName);
        subFormMappingData.put("detail_operator_type", "新增");  // 明细操作类型
        List<JSONObject> tempSubForm = new ArrayList<>();
        tempSubForm.add(subFormMappingData);
        List<JSONObject> tempInsertList = new ArrayList<>();
        tempJson.put("id", crmId);
        tempJson.put("LinkingModule9", tempSubForm);
        tempInsertList.add(tempJson);
        //System.out.println("CRM子表单新增数据 = " + JSONObject.toJSONString(tempInsertList));
        // 更新子表单，不然下次循环查询的数据，还是未新增的状态
        CrmApiUtil.batchUpdateDataByList(zohoRecord.getAccessToken(), tempInsertList, dispatchModuleName);
    }

    private List<JSONObject> filterList(List<JSONObject> tempList) {
        List<JSONObject> list = new ArrayList<>();
        for (JSONObject jsonObject : tempList) {
            JSONObject json = new JSONObject();
            json.put("id", jsonObject.getString("id"));
            json.put("autoid", jsonObject.getString("autoid"));
            json.put("SI", jsonObject.getString("SI"));
            json.put("MainUnitOfMeasurement", jsonObject.getString("MainUnitOfMeasurement"));
            json.put("ProductSupplier", jsonObject.getString("ProductSupplier"));
            json.put("ProductGrade", jsonObject.getString("ProductGrade"));
            json.put("ProductLineManager", jsonObject.getString("ProductLineManager"));
            json.put("PlaceOfOrigin", jsonObject.getString("PlaceOfOrigin"));
            json.put("Warehouse_name", jsonObject.getJSONObject("Warehouse_name"));
            json.put("SalesQty", jsonObject.getString("SalesQty"));
            json.put("ShelfLife", jsonObject.getString("ShelfLife"));
            json.put("Warehouse_number", jsonObject.getString("Warehouse_number"));
            json.put("NetWeight", jsonObject.getString("NetWeight"));
            json.put("Created_By", jsonObject.getString("Created_By"));
            json.put("DangerousGoodsAndGeneralCargo", jsonObject.getString("DangerousGoodsAndGeneralCargo"));
            json.put("DangerousGoodsCCategory", jsonObject.getString("DangerousGoodsCCategory"));
            json.put("Delivery_warehouse", jsonObject.getString("Delivery_warehouse"));
            json.put("dun", jsonObject.getString("dun"));
            json.put("UnitPriceIncludingTax", jsonObject.getString("UnitPriceIncludingTax"));
            json.put("Remark", jsonObject.getString("Remark"));
            json.put("StoragePrecautions", jsonObject.getString("StoragePrecautions"));
            json.put("ProductName", jsonObject.getJSONObject("ProductName"));
            json.put("Product_Code", jsonObject.getString("Product_Code"));
            json.put("Quantity_shipped", jsonObject.getString("Quantity_shipped"));
            json.put("Quantity_invoices", jsonObject.getString("Quantity_invoices"));
            json.put("Lot_number", jsonObject.getString("Lot_number"));
            json.put("changerate", jsonObject.getString("changerate"));
            json.put("UnitPriceWithoutTax", jsonObject.getString("UnitPriceWithoutTax"));
            json.put("TaxfreeAmount", jsonObject.getString("TaxfreeAmount"));
            json.put("EstimatedIdentification", jsonObject.getString("EstimatedIdentification"));
            json.put("Minimum_selling_price", jsonObject.getString("Minimum_selling_price"));
            json.put("SpecialShelfLife", jsonObject.getString("SpecialShelfLife"));
            json.put("ShengChanChangShang", jsonObject.getString("ShengChanChangShang"));
            json.put("Production_date", jsonObject.getString("Production_date"));
            json.put("Total_price_and_tax", jsonObject.getString("Total_price_and_tax"));
            json.put("TaxRate", jsonObject.getString("TaxRate"));
            json.put("TaxAmount", jsonObject.getString("TaxAmount"));
            json.put("freight_unit_price", jsonObject.getString("freight_unit_price"));
            json.put("freight_amount", jsonObject.getString("freight_amount"));
            json.put("SpecificationModel", jsonObject.getString("SpecificationModel"));
            json.put("TransportationPrecautions", jsonObject.getString("TransportationPrecautions"));
            json.put("ERPirowno", jsonObject.getString("ERPirowno"));
            json.put("detail_operator_type", jsonObject.getString("detail_operator_type"));

            list.add(json);
        }

        return list;


    }

    // 获取 子表单映射后的数据
    private JSONObject getSubFormMappingData(JSONObject erpData, List<JSONObject> warehouseData, List<JSONObject> currentStockList,
                                             List<JSONObject> productList, String companyName) {
        JSONObject crmData = new JSONObject();
        crmData.put("autoid", erpData.getString("autoid")); // autoid
        crmData.put("ERPirowno", erpData.getString("irowno")); // 行号

        String cwhcode = erpData.getString("cwhcode");// 仓库编码
        if (StringUtils.isNotBlank(cwhcode)) {
            List<JSONObject> collect = warehouseData.stream().filter(object ->
                    Objects.nonNull(object.getString("warehouse_code")) &&
                            object.getString("warehouse_code").equals(cwhcode) && object.getString("AffiliatedCompany").equals(companyName)).collect(Collectors.toList());
            if (collect.size() > 0) {
                JSONObject temp = new JSONObject();
                temp.put("id", collect.get(0).getString("id"));
                crmData.put("Warehouse_name", temp); // 仓库名称
            }
        }

        String cinvcode = erpData.getString("cinvcode"); // 存货编码
        if (StringUtils.isNotBlank(cinvcode)) {
            List<JSONObject> collect = productList.stream().filter(object ->
                    Objects.nonNull(object.getString("Product_Code")) &&
                            object.getString("Product_Code").equals(cinvcode) && object.getString("AffiliatedCompany").equals(companyName)).collect(Collectors.toList());
            if (collect.size() > 0) {
                JSONObject temp = new JSONObject();
                temp.put("id", collect.get(0).getString("id"));
                crmData.put("ProductName", temp); // 存货名称
            }
        }

        String cBatch = erpData.getString("cBatch"); // 批号
        if (StringUtils.isNotBlank(cBatch)) {
            List<JSONObject> collect = currentStockList.stream().filter(object ->
                    Objects.nonNull(object.getString("Name")) &&
                            object.getString("Name").equals(cBatch) && object.getString("AffiliatedCompany").equals(companyName)).collect(Collectors.toList());
            if (collect.size() > 0) {
                JSONObject temp = new JSONObject();
                temp.put("id", collect.get(0).getString("id"));
                crmData.put("Lot_number", temp); // 批号
            }
        }

        crmData.put("SpecificationModel", erpData.getString("cinvstd")); // 规格型号
        crmData.put("MainUnitOfMeasurement", erpData.getString("cinvm_unit")); // 主计量单位
        crmData.put("UnitPriceIncludingTax", CommonUtil.formatBigDecimal(erpData.getBigDecimal("itaxunitprice"), 2)); // 含税单价
        crmData.put("dun", CommonUtil.formatBigDecimal(erpData.getBigDecimal("iquantity"), 6)); // 吨数
        crmData.put("SalesQty", erpData.getString("inum")); // 件数
        crmData.put("Total_price_and_tax", CommonUtil.formatBigDecimal(erpData.getBigDecimal("isum"), 2)); // 税价合计
        crmData.put("DangerousGoodsAndGeneralCargo", erpData.getString("cinvdefine4")); // 危货普货
        crmData.put("TaxAmount", CommonUtil.formatBigDecimal(erpData.getBigDecimal("inattax"), 2)); // 税额
        crmData.put("UnitPriceWithoutTax", CommonUtil.formatBigDecimal(erpData.getBigDecimal("inatunitprice"), 5)); // 无税单价
        crmData.put("TaxfreeAmount", CommonUtil.formatBigDecimal(erpData.getBigDecimal("inatmoney"), 2)); // 无税金额
        return crmData;
    }

    private List<JSONObject> getCrmMappingDetailData(List<JSONObject> erpList, String companyName, List<JSONObject> productList, String operatorType) {
        List<JSONObject> list = new ArrayList<>();
        for (JSONObject erpData : erpList) {

            JSONObject crmData = new JSONObject();
            crmData.put("KHCompany", companyName); // 所属公司

            if (StringUtils.isNotBlank(erpData.getString("detailCRMId"))) {
                crmData.put("id", erpData.getString("detailCRMId")); // CRMid
            }
            crmData.put("erp_id", erpData.getString("dlid")); // 发货单erp主键
            crmData.put("autoid", erpData.getString("autoid")); // autoid
            crmData.put("detail_operator_type", operatorType); // 明细操作类型
            String dlid = erpData.getString("dlid");
            if (StringUtils.isNotBlank(dlid)) {
                String selectQuery = crmSqlQuery.getDispatchSqlByErpId(dlid, companyName);
                List<JSONObject> erp_id = CrmApiUtil.COQLQuery(zohoRecord.getAccessToken(), selectQuery);
                if (erp_id.size() > 0) {
                    JSONObject dispatchData = erp_id.get(0);
                    String id = dispatchData.getString("id");
                    JSONObject temp = new JSONObject();
                    temp.put("id", id);
                    crmData.put("InvoiceNumber", temp); // 发货单号

                    crmData.put("BusinessType", dispatchData.getString("BusinessType")); // 业务类型
                    crmData.put("SalesType", dispatchData.getString("SalesType")); // 销售类型
                    crmData.put("ShippingDate", dispatchData.getString("ShippingDate")); // 发货日期
                    crmData.put("OrderDate", dispatchData.getString("OrderDate")); // 订单日期

                    if (Objects.nonNull(dispatchData.getJSONObject("order_number"))) {
                        String string = dispatchData.getJSONObject("order_number").toJSONString();
                        crmData.put("order_number", JSONObject.parseObject(string)); // 订单号
                    }

                    if (Objects.nonNull(dispatchData.getJSONObject("Account_Name"))) {
                        String string = dispatchData.getJSONObject("Account_Name").toJSONString();
                        crmData.put("Account_Name", JSONObject.parseObject(string)); // 客户
                    }

                    if (Objects.nonNull(dispatchData.getJSONObject("Salesman"))) {
                        String string = dispatchData.getJSONObject("Salesman").toJSONString();
                        crmData.put("Salesman", JSONObject.parseObject(string)); // 业务员
                    }
                    crmData.put("ShippingAddressnew", dispatchData.getString("ShippingAddressnew")); // 发货地址
                }
            }

            String cinvcode = erpData.getString("cinvcode");// 存货编码
            if (StringUtils.isNotBlank(cinvcode)) {
                List<JSONObject> erp_id = productList.stream().filter(object ->
                        Objects.nonNull(object.getString("Product_Code")) &&
                                object.getString("Product_Code").equals(cinvcode) &&
                                object.getString("AffiliatedCompany").equals(companyName)

                ).collect(Collectors.toList());
                if (erp_id.size() > 0) {
                    String id = erp_id.get(0).getString("id");
                    JSONObject temp = new JSONObject();
                    temp.put("id", id);
                    crmData.put("ProductName", temp); // 产品名称
                }
            }
            crmData.put("Product_Code", erpData.getString("cinvcode")); // 存货编码
            crmData.put("SpecificationModel", erpData.getString("cinvstd")); // 规格型号
            crmData.put("dun", CommonUtil.formatBigDecimal(erpData.getBigDecimal("iquantity"), 6)); // 发货数量（吨）
            crmData.put("UnitPriceIncludingTax", CommonUtil.formatBigDecimal(erpData.getBigDecimal("itaxunitprice"), 2)); // 发货单价（含税）
            crmData.put("Total_price_and_tax", CommonUtil.formatBigDecimal(erpData.getBigDecimal("isum"), 2)); // 发货金额（含税）

            list.add(crmData);
        }
        return list;
    }

    // 获取子表单为空的数据
    private List<JSONObject> getEmptyLinkList(List<JSONObject> crm_updateList) {
        String string = JSONObject.toJSONString(crm_updateList);
        List<JSONObject> emptyList = JSONArray.parseArray(string, JSONObject.class);
        for (JSONObject jsonObject : emptyList) {
            jsonObject.put("LinkingModule9", new ArrayList<>());
        }
        return emptyList;
    }

}

